//
//  NSColor+Hex.swift
//  ConfUIFoundation
//
//  Created by mac on 2021/6/30.
//

import Cocoa
public extension NSColor {
    class func fromHexString(hexString:String)->NSColor {
        return NSColor(hexString:hexString) ?? NSColor.black
    }
    
    
    private convenience init?(hexString:String){
        guard hexString.hasPrefix("#") else {
            return nil
        }
        let hexString:String = String(hexString[hexString.index(hexString.startIndex,offsetBy: 1)...])
        var hexValue:UInt64 = 0
        guard Scanner(string: hexString).scanHexInt64(&hexValue) else {
            return nil
        }
        
        switch hexString.count {
        case 3:
            self.init(hex3:UInt16(hexValue))
        default:
            return nil
        }
        
        
    }
    private convenience init(hex3: UInt16, alpha: CGFloat = 1) {
        let divisor = CGFloat(15)
        let red = CGFloat((hex3 & 0xF00) >> 8) / divisor
        
        let green = CGFloat((hex3 & 0x0F0) >> 4) / divisor
        let blue = CGFloat((hex3 & 0x00F) ) / divisor
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
    private convenience init(hex4: UInt16) {
        let divisor = CGFloat(15)
        let red     = CGFloat((hex4 & 0xF000) >> 12) / divisor
        let green   = CGFloat((hex4 & 0x0F00) >>  8) / divisor
        let blue    = CGFloat((hex4 & 0x00F0) >>  4) / divisor
        let alpha   = CGFloat( hex4 & 0x000F       ) / divisor
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
    private convenience init(hex6: UInt32, alpha: CGFloat = 1) {
        let divisor = CGFloat(255)
        let red     = CGFloat((hex6 & 0xFF0000) >> 16) / divisor
        let green   = CGFloat((hex6 & 0x00FF00) >>  8) / divisor
        let blue    = CGFloat( hex6 & 0x0000FF       ) / divisor
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }

    private convenience init(hex8: UInt32) {
        let divisor = CGFloat(255)
        let red     = CGFloat((hex8 & 0xFF000000) >> 24) / divisor
        let green   = CGFloat((hex8 & 0x00FF0000) >> 16) / divisor
        let blue    = CGFloat((hex8 & 0x0000FF00) >>  8) / divisor
        let alpha   = CGFloat( hex8 & 0x000000FF       ) / divisor
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
}
